package com.spoplar.lsm;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.ws.rs.core.MediaType;

import org.json.JSONException;
import org.json.JSONObject;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
import com.sun.jersey.core.util.MultivaluedMapImpl;

public class Smsapi {

	private static  String TOKEN ="key-";
	private static  String SEND_URL ="";
	private static  String MSG_SIGN = "";
	
	static {
		Properties properties = new Properties();
		FileInputStream inputStream;
		try {
			File file = new File("config/lsm.properties");
			System.out.println(file.getAbsoluteFile());
			inputStream = new FileInputStream(file);
			properties.load(inputStream);
			inputStream.close();
			TOKEN = properties.getProperty("token");
			SEND_URL = properties.getProperty("send_url");
			MSG_SIGN = properties.getProperty("msg_sign");
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	//发送消息
	public Boolean sendMsg(String mobile,String msg) {
		
		Client client = Client.create();
		client.addFilter(new HTTPBasicAuthFilter("api", TOKEN));
		
		WebResource webResource = client.resource(SEND_URL);
		
		MultivaluedMapImpl formdata = new MultivaluedMapImpl();
		formdata.add("mobile", mobile);
		formdata.add("message", msg+MSG_SIGN);
		
		ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class,formdata);
		
		String textEntity = response.getEntity(String.class);
		int status = response.getStatus();
		//System.out.println(textEntity);
		//System.out.println(status);
		if(status==200){
		   return isNormal(textEntity);
		}
		return false;
	}
	//是否正常
	public boolean isNormal(String response){
		try {
			JSONObject jsonObject =  new JSONObject(response);
			int error_code = jsonObject.getInt("error");
			String error_msg = jsonObject.getString("msg");
			if(error_code == 0){
				return true;
			}else{
				String log_msg="send message failed,code is"+error_code+",msg is"+error_msg;
				Logger.getLogger(Smsapi.class.getName()).log(Level.SEVERE,log_msg);
				return false;
			}
			
		} catch (JSONException ex) {
			Logger.getLogger(Smsapi.class.getName()).log(Level.SEVERE,null,ex);
		}
		
		return false;
	}
}
